<template>
  <div id="company-detail" height="100vh" >
      <el-container style="flex: 1; display: flex; ">
        <el-main>
          <div class="header-row">
            <el-button @click="goBack" class="back-btn">
              <i class="el-icon-arrow-left"></i> 返回
            </el-button>
            <h2>企业详细信息</h2>
          </div>

          <div class="recruiter-detail">
            <div class="header">
              <img :src="company.avatar || defaultAvatar" class="logo">
              <div>
                <h3>{{ company.name }}</h3>
                <span class="industry-badge">{{ company.companyIndustry }}</span>
              </div>
            </div>

            <!-- 企业信息表格 -->
            <div class="company-info-table">
              <div class="table-row">
                <div class="table-cell label-cell">企业ID</div>
                <div class="table-cell value-cell">{{ company.companyId }}</div>
                <div class="table-cell label-cell">企业地址</div>
                <div class="table-cell value-cell">{{ company.location }}</div>
              </div>

              <div class="table-row">
                <div class="table-cell label-cell">创建日期</div>
                <div class="table-cell value-cell">{{ formatDate(company.createDate) }}</div>
                <div class="table-cell label-cell">休息制度</div>
                <div class="table-cell value-cell">{{ getWorkTimeTypeText(company.workTimeType) }}</div>
              </div>

              <div class="table-row">
                <div class="table-cell label-cell">工作时间</div>
                <div class="table-cell value-cell">{{ formatWorkTime(company) }}</div>
                <div class="table-cell label-cell">企业规模</div>
                <div class="table-cell value-cell">{{ company.scale || '未说明' }}</div>
              </div>
            </div>

            <!-- 企业简介 -->
            <div class="company-introduction">
              <h4>企业简介</h4>
              <p>{{ company.companyIntroduction || '暂无简介' }}</p>
            </div>

            <!-- 企业用户信息 -->
            <div class="company-users">
              <h4>企业用户信息</h4>
              <div class="user-cards">
                <div v-for="user in companyUsers" :key="user.userId" class="user-card" @click="showUserDetail(user)">
                  <div class="recruiter-avatar">
                    <img :src="user.avatar || defaultAvatar">
                  </div>
                  <div class="user-info">
                    <span class="user-name">{{ user.name }}</span>
                    <span class="user-position">{{ getUserTypeText(user.type) }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 企业岗位信息 -->
            <div class="company-jobs">
              <h4>企业岗位信息</h4>
              <div class="job-cards">
                <div v-for="position in companyPositions" :key="position.positionId" class="job-card"
                  @click="showPositionDetail(position)">
                  <div class="job-title">{{ position.positionName || '未命名岗位' }}</div>
                  <div class="job-salary">{{ getSalaryRange(position) || '-' }}</div>
                  <div class="job-meta">
                    <span class="job-tag">{{ position.positionType || '-' }}</span>
                    <span class="job-date">发布于 {{ getDaysAgo(position.startAt) }} 天前</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 用户详情弹框 -->
          <UserResumeDialog :visible.sync="userDialogVisible" :user="currentUser" :defaultAvatar="defaultAvatar">
          </UserResumeDialog>

          <!-- 岗位详情弹框 -->
          <PositionDialog :visible.sync="positionDialogVisible" :position="currentPosition"
            :defaultAvatar="defaultAvatar"></PositionDialog>
        </el-main>
    </el-container>
  </div>
</template>

<script>
import UserResumeDialog from "../components/ManaUserDialog.vue";
import PositionDialog from "../components/positionDialog.vue";
import { getCompanyMessage } from "@/util/manager_api/company";

export default {
  components: {
    UserResumeDialog,
    PositionDialog,
  },
  data() {
    return {
      company: {},
      defaultAvatar: 'https://picsum.photos/200/200?random=0',
      companyUsers: [],
      companyPositions: [],
      userDialogVisible: false,
      positionDialogVisible: false,
      companyId: '',
      currentUser: {},
      currentPosition: {},
    };
  },
  created() {
    // 从本地存储获取companyId
    this.companyId = localStorage.getItem('companyId');
    // this.companyId = this.$route.params.companyId || savedCompanyId;
    if (this.companyId) {
      this.fetchCompanyMessage();
    } else {
      console.error('未获取到companyId');
      this.$router.back();
    }
  },
  methods: {
    async fetchCompanyMessage() {
      try {
        const params = {
          companyId: Number(this.companyId),
        };
        const response = await getCompanyMessage(params);
        this.company = response.data.data;

        // 处理岗位数据，确保数据结构完整
        this.companyPositions = response.data.data.mcrossComJobMessageRespList.map(position => {
          return {
            ...position,
            mcrossComUserMessageResp: position.mcrossComUserMessageResp || {},
          };
        });

        this.companyUsers = response.data.data.mcrossComUserMessageRespList;
      } catch (error) {
        console.error('获取具体信息失败:', error);
      }
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '未提供';

      try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) {
          return '日期格式错误';
        }
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: 'long',
          day: 'numeric',
          hour: '2-digit',
          minute: '2-digit'
        });
      } catch (error) {
        console.error('日期解析失败:', error);
        return '日期解析失败';
      }
    },

    // 格式化工作时间
    formatWorkTime(company) {
      if (!company.workDayStartTime || !company.workDayEndTime) return '未设置';

      const startTime = new Date(company.workDayStartTime);
      const endTime = new Date(company.workDayEndTime);

      const startHour = startTime.getHours().toString().padStart(2, '0');
      const startMinute = startTime.getMinutes().toString().padStart(2, '0');
      const endHour = endTime.getHours().toString().padStart(2, '0');
      const endMinute = endTime.getMinutes().toString().padStart(2, '0');

      return `${startHour}:${startMinute} - ${endHour}:${endMinute}`;
    },

    //计算发布天数
    getDaysAgo(timeStr) {
      try {
        if (!timeStr) return '未提供';
        const targetDate = new Date(timeStr);
        const now = new Date();
        const timeDiff = now - targetDate;
        const daysAgo = Math.floor(timeDiff / (24 * 60 * 60 * 1000));
        return daysAgo >= 0 ? daysAgo : '即将发布';
      } catch (error) {
        console.error('时间解析失败:', error);
        return '未知';
      }
    },

    // 获取工作时间类型文本
    getWorkTimeTypeText(type) {
      const typeMap = {
        'SINGLE_REST': '单休',
        'DOUBLE_REST': '双休',
        'FLEXIBLE': '弹性工作制',
      };
      return typeMap[type] || type;
    },
    //获取企业用户类型文本
    getUserTypeText(type) {
      const typeMap = {
        'BOSS': '老板',
        'MANAGEMENT': '管理层',
        'RECRUITER': '招聘人员'
      };
      return typeMap[type] || type;
    },
    // 获取薪资范围文本
    getSalaryRange(position) {
      if (position.lowestSalaryMonth !== undefined && position.highestSalaryMonth !== undefined) {
        return `${position.lowestSalaryMonth}-${position.highestSalaryMonth} 元/月`;
      }
      return position.salary || '-';
    },

    // 显示用户详情弹框
    showUserDetail(user) {
      if (user && typeof user === 'object') {
        this.userDialogVisible = true;
        this.currentUser = { ...user, stype: 'recruiter' };
      } else {
        console.error('用户数据无效，必须为对象类型');
        this.$message.error('用户数据加载失败');
      }
    },

    // 显示岗位详情弹框
    showPositionDetail(position) {
      if (position && typeof position === 'object') {
        this.positionDialogVisible = true;
        // 确保传递的岗位数据结构完整
        this.currentPosition = {
          ...position,
          mcrossComUserMessageResp: position.mcrossComUserMessageResp || {},
        };
      } else {
        console.error('岗位数据无效，必须为对象类型');
        this.positionDialogVisible = false;
        this.$message.error('岗位数据加载失败');
      }
    },
    goBack() {
      localStorage.removeItem('companyId');
      this.$router.back();
    },
  },
};
</script>

<style scoped>
@import url('./ManaComDetail.css')
</style>
